package interfaces;

import java.util.ArrayList;
import java.util.Timer;
import java.util.TimerTask;

import negocio.ContatoLocal;
import negocio.Conversa;
import negocio.UsuarioLocal;

import com.example.falai.R;

import databases.ContatosDS;
import databases.Helper;
import databases.MensagemDS;
import databases.UsuarioLocalDS;

import android.os.Bundle;
import android.os.Handler;
import android.app.Activity;
import android.content.ContentValues;
import android.content.SharedPreferences;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

public class MensagemActivity extends Activity {
	
	private String curNick;
	private String curContato;
	private Bundle extras;
	private MensagemDS mensagem;
	ArrayList<Conversa>conversaArrayList;
	private Helper db;
	private UsuarioLocal user;
	private UsuarioLocalDS userDS;
	private ContatoLocal contato;
	private ContatosDS contatoDS;
	EditText msg;
	EditText conversaLV;
	Button enviar;
	ListView listView;
	
    private Timer timerAtual = new Timer();
    private TimerTask task;
    private final Handler handler = new Handler();

	
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_mensagem);
		
		curContato = "";
		
		extras = getIntent().getExtras();
				
		if(extras != null)
		{
			curContato = extras.getString("nickContato");
			contatoDS = new ContatosDS(this);
			contatoDS.open();
			contato = contatoDS.getContatoLocal(curContato);
			contatoDS.close();
			
			curNick = extras.getString("user");
			userDS = new UsuarioLocalDS(this);
			userDS.open();
			user = userDS.getUsuarioLocal(curNick);
			userDS.close();

			listView = (ListView) findViewById(R.id.lv_conversa);
			atualizaConversa();
		}
		
		ativaTimer();
		addListenerOnButton();
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.mensagem, menu);
		return true;
	}
	public void addListenerOnButton() {
		
	    mensagem = new MensagemDS(this);
		enviar = (Button) findViewById(R.id.btn_enviar);
		enviar.setOnClickListener(new OnClickListener() {
 			@Override
			public void onClick(View arg0) {
 				msg = (EditText) findViewById(R.id.tfd_mensagem);
 				listView = (ListView) findViewById(R.id.lv_conversa);
 				
 				if(msg.getText().toString().isEmpty()){
 					Toast.makeText(MensagemActivity.this,"Digite alguma mensagem ", Toast.LENGTH_SHORT).show();
 				}
 				else
 				{
 					Conversa conversa = new Conversa();
 					conversa.set_id_sender((int) user.getId());
 					conversa.set_id_target((int) contato.getId());
 					conversa.setMensagem(msg.getText().toString());
 					
 					//TODO 
 					mensagem.open();
 					mensagem.conversaDS(conversa);
 					mensagem.close();
 					msg.setText("");
 					
 					montaConversa();
 				}
 			}
		});
	}

	private void montaConversa(){
		mensagem = new MensagemDS(this);
		mensagem.open();
		conversaArrayList = mensagem.getAll((int) contato.getId());
		listView.setAdapter(new MyCustomAdapter());
		listView.setCacheColorHint(0);
	}
	
	private void atualizaConversa(){
		mensagem = new MensagemDS(this);
		ContentValues values = new ContentValues();
		values.put("sender", (int) user.getId());
		values.put("target", (int) contato.getId());
		
		conversaArrayList = mensagem.atualizaMensagem(values);
		listView.setAdapter(new MyCustomAdapter());
		listView.setCacheColorHint(0);
	}

	
	private void ativaTimer(){
        task = new TimerTask() {
            public void run() {
                    handler.post(new Runnable() {
                            public void run() {
                            	atualizaConversa();
                            }
                   });
            }};
           
            timerAtual.schedule(task, 300, 300); 
    }

	
	/**
	 * This class serves as the adapter that draws rows and provides data to the list 
	 * @author aman
	 *
	 */
	class MyCustomAdapter extends BaseAdapter {
		
		/**
		 * returns the count of elements in the Array that is used to draw the text in rows 
		 * @see android.widget.Adapter#getCount()
		 */
		@Override
		public int getCount() {
			return conversaArrayList.size();
		}

		/**
		 * Get the data item associated with the specified position in the data set.
		 * (not Implemented at this point)
		 * @param position The position of the row that was clicked (0-n)
		 * @see android.widget.Adapter#getItem(int)
		 */
		@Override
		public String getItem(int position) {
			// TODO Auto-generated method stub
			return null;
		}

		/**
		 * Get the row id associated with the specified position in the list.
		 * (not implemented at this point)
		 * @param position The position of the row that was clicked (0-n)
		 * @see android.widget.Adapter#getItemId(int)
		 */
		@Override
		public long getItemId(int position) {
			// TODO Auto-generated method stub
			return position;
		}

		/**
		 * Returns the complete row that the System draws.
		 * It is called every time the System needs to draw a new row;
		 * You can control the appearance of each row inside this function.
		 * @param position The position of the row that was clicked (0-n)
		 * @param convertView The View object of the row that was last created. null if its the first row
		 * @param parent The ViewGroup object of the parent view
		 * @see android.widget.Adapter#getView(int, android.view.View, android.view.ViewGroup)
		 */

		public View getView(int position, View convertView, ViewGroup parent) {
			LayoutInflater inflater = getLayoutInflater();
			View row;
			String even_color,odd_color;
			SharedPreferences prefList = getSharedPreferences("PrefsFile",MODE_PRIVATE);;
			even_color = prefList.getString("even_bubble_color","pink");
			odd_color = prefList.getString("odd_bubble_color","green");
			int even_color_id=getResources().getIdentifier(even_color,"drawable","com.teks.chilltwit"),
				odd_color_id=getResources().getIdentifier(odd_color,"drawable","com.teks.chilltwit");
			ImageView even_view,odd_view;
//			if(position!=data.length-1){
			if(conversaArrayList.get(position).get_id_sender()==user.getId()){
				row = inflater.inflate(R.layout.list_row_layout_even, parent, false);
				TextView textLabel = (TextView) row.findViewById(R.id.text);
				
				textLabel.setText(conversaArrayList.get(position).getMensagem());
				
			}else{
				row = inflater.inflate(R.layout.list_row_layout_odd, parent, false);
				TextView textLabel = (TextView) row.findViewById(R.id.text);
				
				textLabel.setText(conversaArrayList.get(position).getMensagem());
			}

			return (row);
		}
	}

	
}
